<template>
  <Row>
    <Col :span="24">
      <Table border :columns="columns" :data="tableData" size="small" />
      <Modal v-model="dialogvisible" title="修改设备信息">
        <Form :rules="rules" :model="formData" ref="formRef" label-width="120">
          <FormItem label="所属企业:">
            <Select v-model="formData.companyId" disabled>
              <Option
                v-for="item in companyList"
                :value="item.id"
                :key="item.value"
                :label="item.name"
              />
            </Select>
          </FormItem>
          <FormItem label="所属区域:" prop="groupId">
            <Select v-model="formData.groupId">
              <Option
                v-for="item in groupList"
                :value="item.id"
                :key="item.value"
                :label="item.name"
              />
            </Select>
          </FormItem>
          <FormItem label="设备ID:" prop="deviceId">
            <Input
              v-model.trim="formData.deviceId"
              placeholder="请输入设备ID..."
            />
          </FormItem>
          <FormItem label="设备类型:">
            <Select v-model="formData.deviceType" disabled>
              <Option
                v-for="(item, index) in deviceTypes"
                :value="item.id"
                :key="index"
                :label="item.name"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="采集方式:">
            <Select v-model="formData.collectType" disabled>
              <Option
                v-for="item in collectTypes"
                :value="item.desCode"
                :key="item.index"
                :label="item.des"
                >{{ item.des }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="采集频率">
            <Input v-model="formData.rate" disabled />
          </FormItem>
          <FormItem label="设备名称:" prop="name">
            <Input
              v-model.trim="formData.name"
              placeholder="请输入设备名称..."
            />
          </FormItem>
          <FormItem label="设备别名:" prop="alias">
            <Input
              v-model.trim="formData.alias"
              placeholder="请输入设备别名..."
            />
          </FormItem>
          <FormItem label="设备位置:" prop="location">
            <Input
              v-model.trim="formData.location"
              placeholder="请输入设备位置..."
            />
          </FormItem>
          <FormItem label="网关端口:" v-if="!isDtu">
            <Select
              v-model="formData.gatewayPort"
              placeholder="请选择网关端口..."
              disabled
            >
              <Option
                v-for="item in gatewayPortList"
                :value="item.port"
                :key="item.port"
                :label="item.port"
              />
            </Select>
          </FormItem>
          <FormItem label="网关地址码:" prop="gatewayCode" v-if="!isDtu">
            <InputNumber
              v-model="formData.gatewayCode"
              placeholder="请输入网关地址码..."
              style="width:100%;"
            />
          </FormItem>
          <FormItem
            label="设备级别:"
            prop="deviceLevel"
            v-if="row.transformerStructure"
          >
            <Select
              v-model="formData.deviceLevel"
              @on-change="onDeviceLevelChange"
              placeholder="请选择设备级别..."
            >
              <Option
                v-for="(item, index) in deviceLevelList"
                :value="item.id"
                :label="item.name"
                :key="index"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <!-- 二级表 deviceLevel===2 -->
          <FormItem label="上级设备:" prop="deviceParent" v-if="isSecond">
            <Select
              v-model="formData.deviceParent"
              placeholder="请选择设备级别..."
            >
              <Option
                v-for="item in deviceLevelFirst"
                :value="item.id"
                :key="item.value"
                :label="item.name"
              />
            </Select>
          </FormItem>
          <!-- 三级表 deviceLevel===3-->
          <FormItem label="上级设备:" prop="deviceParent" v-if="isThree">
            <Row>
              <Col span="11">
                <!-- 变压器列表 -->
                <Select v-model="parentId1" @on-change="onParent1Change">
                  <Option
                    v-for="item in deviceLevelFirst"
                    :value="item.id"
                    :key="item.id"
                    :label="item.name"
                  />
                </Select>
              </Col>
              <Col span="2" style="text-align:center;">-</Col>
              <Col span="11">
                <!-- 二级表列表 -->
                <Select
                  v-model="formData.deviceParent"
                  placeholder="请选择设备级别..."
                >
                  <Option
                    v-for="item in deviceLevelSecond"
                    :value="item.id"
                    :key="item.id"
                    :label="item.name"
                  />
                </Select>
              </Col>
            </Row>
          </FormItem>
          <!-- 四级表  deviceLevel===4-->
          <FormItem label="上级设备:" prop="deviceParent" v-if="isFour">
            <Row>
              <Col span="7">
                <!-- 变压器列表 -->
                <Select v-model="parentId1" @on-change="onParent1Change">
                  <Option
                    v-for="item in deviceLevelFirst"
                    :value="item.id"
                    :key="item.id"
                    :label="item.name"
                  />
                </Select>
              </Col>
              <Col span="1" style="text-align:center;">-</Col>
              <Col span="7">
                <!-- 二级表列表 -->
                <Select
                  v-model="parentId2"
                  placeholder="请选择设备级别..."
                  @on-change="onParent2Change"
                >
                  <Option
                    v-for="item in deviceLevelSecond"
                    :value="item.id"
                    :key="item.id"
                    :label="item.name"
                  />
                </Select>
              </Col>
              <Col span="1" style="text-align:center;">-</Col>
              <Col span="7">
                <!-- 三级表列表 -->
                <Select
                  v-model="formData.deviceParent"
                  placeholder="请选择设备级别..."
                >
                  <Option
                    v-for="item in deviceLevelThird"
                    :value="item.id"
                    :key="item.id"
                    :label="item.name"
                  />
                </Select>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="断路功能:" prop="disconState">
            <i-switch v-model="formData.disconState">
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>
          <FormItem label="是否启用:" prop="enable">
            <i-switch v-model="formData.enable">
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>
          <FormItem
            label="软件计算:"
            prop="calculateStatus"
            v-if="deviceLevel != 4"
          >
            <i-switch v-model="formData.calculateStatus">
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="onCancle">取消</Button>
          <Button type="primary" @click="onSubmit">完成</Button>
        </div>
      </Modal>
    </Col>
  </Row>
</template>
<script>
import {
  getCompanyListOfNew,
  getGroupList,
  getDeviceType,
  getGatewayType,
  getGatewayList,
  editDevice,
  getParentDeviceList
} from "@/api";
import { generateRules, deviceLevelList } from "../utils";
function filterText(bool) {
  if (bool) {
    return {
      text: "是",
      color: "success"
    };
  }
  return {
    text: "否",
    color: "error"
  };
}

const gatewayParams = [
  {
    title: "网关端口",
    align: "center",
    key: "gatewayPort"
  },
  {
    title: "网关地址码",
    align: "center",
    key: "gatewayCode"
  }
];

function genColumns(vm) {
  return [
    {
      title: "所属企业",
      key: "company",
      align: "center"
    },
    {
      title: "所属区域",
      key: "group",
      align: "center"
    },
    {
      title: "采集方式",
      align: "center",
      render(h, params) {
        const { collectType } = params.row,
          result = vm.collectTypeList.find(t => t.desCode === collectType),
          text = result ? result.des : "";
        return h("span", text);
      }
    },
    {
      title: "设备名称",
      align: "center",
      key: "name"
    },
    {
      title: "设备别名",
      align: "center",
      key: "alias"
    },
    {
      title: "设备位置",
      align: "center",
      key: "location"
    },
    {
      title: "设备ID",
      align: "center",
      key: "deviceId"
    },
    {
      title: "设备级别",
      align: "center",
      render: (h, params) => {
        const { deviceLevel } = params.row;
        const currentDevice = deviceLevelList.find(t => t.id === deviceLevel);
        const text = currentDevice ? currentDevice.name : "";
        return h("span", text);
      }
    },
    {
      title: "是否断路",
      align: "center",
      render: (h, params) => {
        const { disconState } = params.row;
        const { text, color } = filterText(disconState);
        return h(
          "Tag",
          {
            props: {
              color
            }
          },
          text
        );
      }
    },
    {
      title: "是否启用",
      align: "center",
      render: (h, params) => {
        const { enable } = params.row;
        const { text, color } = filterText(enable);
        return h(
          "Tag",
          {
            props: {
              color
            }
          },
          text
        );
      }
    },
    {
      title: "采集频率",
      align: "center",
      render: (h, params) =>
        h(
          "span",
          params.row.collectRate ? params.row.collectRate + "分钟" : "-"
        )
    },
    {
      title: "软件计算",
      align: "center",
      render: (h, params) => {
        const { calculateStatus } = params.row;
        const { text, color } = filterText(calculateStatus);
        return h(
          "Tag",
          {
            props: {
              color
            }
          },
          text
        );
      }
    }
  ];
}

function genOperClounms(vm) {
  return {
    title: "操作",
    align: "center",
    render: (h, params) => {
      return h(
        "Button",
        {
          props: {
            type: "error",
            size: "small"
          },
          on: {
            click: () => {
              vm.handelEdit();
            }
          }
        },
        "编辑"
      );
    }
  };
}

export default {
  mounted() {
    this.initState();
  },
  props: {
    row: {
      type: Object,
      default: {}
    },
    isDtu: {
      type: Boolean,
      default: false
    },
    collectTypeList: {
      type: Array,
      default: []
    }
  },
  watch: {
    row: {
      deep: true,
      handler() {
        this.initState();
      }
    }
  },
  data() {
    return {
      collectRate: "",
      columns: [],
      tableData: [],
      companyList: [],
      deviceLevelList: [...deviceLevelList],
      groupList: [],
      deviceTypes: [],
      collectTypes: [],
      gatewayPortList: [],
      formData: {},
      dialogvisible: false,
      parentId1: "",
      parentId2: "",
      rules: generateRules(),
      deviceLevel: 0,
      // 变压器列表
      deviceLevelFirst: [],

      // 二级表列表
      deviceLevelSecond: [],

      // 三级表列表
      deviceLevelThird: []
    };
  },
  computed: {
    isSecond() {
      return this.deviceLevel === 2 ? true : false;
    },
    isThree() {
      return this.deviceLevel === 3 ? true : false;
    },
    isFour() {
      return this.deviceLevel === 4 ? true : false;
    }
  },
  methods: {
    initState() {
      const columns = genColumns(this);
      if (!this.isDtu) {
        this.columns = columns
          .concat(gatewayParams)
          .concat(genOperClounms(this));
      } else {
        this.columns = columns.concat(genOperClounms(this));
      }

      this.deviceLevel = this.row.deviceLevel;
      this.tableData = [this.row];
    },
    handelEdit() {
      this.dialogvisible = true;
      this.$refs.formRef.resetFields();
      this.formData = JSON.parse(JSON.stringify(this.row));
      this.formData["rate"] = this.row.collectRate;
      this.deviceLevel = this.row.deviceLevel;
      // this.collectRate = this.row.collectRate
      const formData = JSON.parse(JSON.stringify(this.row));
      this.getCompanyList();
      this.getGroupList(this.row.companyId);
      this.getDeviceTypeList();
      this.getCollectTypeList();
      if (!this.isDtu) {
        let collectType = this.row.collectType;
        this.getGatewayTypeList(collectType);
      }

      // 如果设备是二级表，获取变压器1级表列表
      if (formData.deviceLevel === 2) {
        // this.formData["deviceParent"] = params.parentId;
        this.getFristList();
      } else if (formData.deviceLevel === 3) {
        // 三级表获取二级表列表
        this.getSecondList();
      } else if (formData.deviceLevel === 4) {
        // 四级表获取三级表二级表列表获取变压器列表
        this.getThirdList();
      }
    },
    // 二级表获取变压器列表
    getFristList() {
      const vm = this;
      const params = {
        companyId: vm.formData.companyId,
        level: 1,
        parentId: null
      };
      getParentDeviceList(params).then(res => {
        if (res.code === 200) {
          vm.deviceLevelFirst = res.data;
        }
      });
    },

    // 三级表获取二级表列表获取变压器列表
    getSecondList() {
      const vm = this;
      const parentId = vm.formData.deviceParent;
      const companyId = vm.formData.companyId;
      const params = {
        companyId,
        level: 2,
        parentId: null
      };
      getParentDeviceList(params).then(res => {
        if (res.code === 200) {
          this.deviceLevelSecond = res.data;
          const result0 = res.data.find(t => t.id === parentId);
          if (!result0) {
            vm.deviceLevelThird = [];
            vm.deviceLevelSecond = [];
          } else {
            vm.parentId1 = result0.deviceParent;
          }

          getParentDeviceList({
            companyId,
            level: 1
          }).then(res1 => {
            if (res1.code === 200) {
              vm.deviceLevelFirst = res1.data;
            } else {
              vm.deviceLevelFirst = [];
            }
          });
        } else {
          this.deviceLevelSecond = [];
        }
      });
    },

    // 四级表获取三级表获取二级表获取变压器列表
    getThirdList() {
      const vm = this;
      const parentId = vm.formData.deviceParent;
      const companyId = vm.formData.companyId;
      const params = {
        companyId,
        level: 3
      };
      getParentDeviceList(params).then(res0 => {
        if (res0.code === 200) {
          vm.deviceLevelThird = res0.data;
          let result0 = res0.data.find(t => t.id === parentId);
          if (!result0) {
            vm.deviceLevelThird = [];
            vm.deviceLevelSecond = [];
            getParentDeviceList({ companyId, level: 1 }).then(res2 => {
              if (res2.code === 200) {
                vm.deviceLevelFirst = res2.data;
              }
            });
            return false;
          }
          vm.parentId2 = result0.deviceParent;

          getParentDeviceList({
            companyId,
            level: 2
          }).then(res1 => {
            if (res1.code === 200) {
              vm.deviceLevelSecond = res1.data;
              vm.parentId1 = res1.data.find(
                t => t.id === vm.parentId2
              ).deviceParent;
              getParentDeviceList({ companyId, level: 1 }).then(res2 => {
                if (res2.code === 200) {
                  vm.deviceLevelFirst = res2.data;
                }
              });
            }
          });
        }
      });
    },

    // 设备级别 change
    onDeviceLevelChange(id) {
      this.deviceLevel = id;
      // 设备级别为变压器不需要获取列表
      if (id === 1) return false;

      // 如果id为4 手动置空二级表和三级表的列表和选中的参数
      if (id === 4) {
        this.deviceLevelSecond = []; // 二级表列表
        this.deviceLevelThird = []; // 三级表列
        this.parentId2 = null;
      }

      // 设备类型为非变压器需要获取变压器列表
      const params = {
        companyId: this.formData.companyId,
        level: 1,
        parentId: null
      };

      this.parentId1 = null;
      this.formData.deviceParent = null;
      getParentDeviceList(params).then(res => {
        if (res.code === 200) {
          this.deviceLevelFirst = res.data;
        } else {
          this.deviceLevelFirst = [];
        }
      });
    },

    // 变压器 change 修改二级表列表
    onParent1Change(parentId) {
      if (!parentId) return false;
      const vm = this;
      const params = {
        companyId: vm.formData.companyId,
        level: 2,
        parentId
      };
      this.parentId2 = "";
      this.formData.deviceParent = "";
      if (vm.formData.deviceLevel === 4) {
        this.deviceLevelThird = [];
      }
      getParentDeviceList(params).then(res => {
        if (res.code === 200) {
          this.deviceLevelSecond = res.data;
        } else {
          this.deviceLevelSecond = [];
        }
      });
    },

    // 二级表列表 change
    onParent2Change(parentId) {
      if (!parentId) return false;
      const vm = this;
      const params = {
        companyId: vm.formData.companyId,
        level: 3,
        parentId
      };
      this.formData.deviceParent = null;
      getParentDeviceList(params).then(res => {
        if (res.code === 200) {
          this.deviceLevelThird = res.data;
        } else {
          this.deviceLevelThird = [];
        }
      });
    },

    onCancle() {
      this.dialogvisible = false;
    },

    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let params = {
            ...this.formData
          };
          editDevice(params).then(res => {
            if (res.code === 200) {
              this.$Message.success("操作成功");
              this.dialogvisible = false;
              this.initState();
              this.$emit("afterSave");
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },

    getCompanyList() {
      const vm = this;
      const params = {
        page: 1,
        size: 1000
      };
      getCompanyListOfNew(params).then(res => {
        if (res.code === 200) {
          vm.companyList = res.data.list;
        } else {
          vm.companyList = [];
        }
      });
    },

    getGroupList(companyId) {
      const vm = this;
      getGroupList({ companyId }).then(res => {
        if (res.code === 200) {
          vm.groupList = res.data.list;
        }
      });
    },

    // 获取设备类型列表
    getDeviceTypeList() {
      getDeviceType().then(res => {
        if (res.code === 200) {
          this.deviceTypes = res.data;
        }
      });
    },

    // 获取采集类型列表
    getCollectTypeList() {
      getGatewayType().then(res => {
        if (res.code === 200) {
          this.collectTypes = res.data;
        }
      });
    },

    // 网关端口
    getGatewayTypeList(type) {
      if (type && type !== 0) {
        const params = { type };
        getGatewayList({ params }).then(res => {
          this.gatewayPortList = res.data;
        });
      }
    }
  }
};
</script>
